<?php
/**
 * This is the model class for table "post".
 *
 * The followings are the available columns in table 'post':
 * @property integer $id
 * @property integer $cid
 * @property string $title
 * @property string $content
 * @property string $add_time
 *
 * The followings are the available model relations:
 */
class Post extends CActiveRecord
{
	private $_oldTags;

	private $_markdown;

	const TEMPCACHE_KEY = 'posttemp';

	/**
	 * Returns the static model of the specified AR class.
	 * @return Post the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{post}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('cid, title, content', 'required'),
			array('cid', 'numerical', 'integerOnly'=>true),
			array('title', 'length', 'max'=>128),
			//array('tag', 'match', 'pattern' => '/^[\w\s,]+$/', 'message' => '标签只能是英文单词，用英文逗号隔开！'),
			array('tag', 'normalizeTag'),
			array('top', 'type', 'type' => 'boolean'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, cid, title, content, add_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		    'category' => array(self::BELONGS_TO, 'Category', 'cid', 'select' => 'name'),
		    'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'order' => 'comments.add_datetime desc'),
		    'commentCount' => array(self::STAT, 'Comment', 'post_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'cid' => 'Category',
			'tag' => '标签',
			'title' => 'Title',
			'content' => 'Content',
			'add_time' => 'Add Time',
		);
	}

	/**
	 * before validate,set title and content from content_markdown
	 */
	public function beforeValidate()
	{
		if (parent::beforeValidate()) {
//		    $content = preg_replace('/\r?\n/', "\n", $this->content_markdown);
		    //$content = $this->content_markdown;
//		    $this->title = strstr($content, "\n", true);
//		    $this->content = strstr($content, "\n");
		    return true;
		} else
			return false;
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search(array $pagination = null)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria(array(
		    'order' => 'top desc,update_time desc'
		));

		$criteria->compare('id',$this->id);
		$criteria->compare('uid',Yii::app()->user->id);
		$criteria->compare('cid',$this->cid);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('tag',$this->tag,true);
		$criteria->compare('content',$this->content,true);
		$criteria->compare('add_time',$this->add_time,true);

		if (null === $pagination) {
		    $pagination = array(
		        'pageVar' => 'page',
		        'pageSize' => Yii::app()->params['postsPerPage']
		    );
		}
		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		    'pagination' => $pagination,
		));
	}

	public function beforeSave()
	{
	    if (parent::beforeSave()) {
	    	if ($this->isNewRecord) {
		       	$this->add_time = $this->update_time = date('Y-m-d H:i:s');
		        $this->uid = yii::app()->user->id;
	    	} else
	    		$this->update_time = date('Y-m-d H:i:s');

	        return true;
	    } else
	        return false;
	}

	public function afterSave()
	{
		parent::afterSave();
		Tag::model()->updateFrequency($this->tag, $this->_oldTags);	//update the frequency of tag;
		//clear temp cache
		$this->clearTempCache();
	}

	public function normalizeTag()
	{
		$this->tag = Tag::array2string(array_unique(Tag::string2array($this->tag)));
	}

	public function afterFind()
	{
		parent::afterFind();
	    $this->_oldTags = $this->tag;
	   // $this->add_time = strtotime($this->add_time);
	}

	public function afterDelete()
	{
		parent::afterDelete();
		Tag::model()->updateFrequency($this->tag, '');
	}

	public function getTags()
	{
		return Tag::string2array($this->tag);
	}

	public function getCategoryData()
	{
	    return new Category;
	}

	public function setMarkdown()
	{
		$this->_markdown = new Markdown();
	}

	public function markdown()
	{
		if (null === $this->_markdown)
			$this->setMarkdown();

		return $this->_markdown;
	}

	public function tempCacheAttributes()
	{
		return array('id', 'cid', 'content_markdown', 'title', 'content', 'tag');
	}


	public function addTempCache()
	{
	    $data = array();
		foreach ($this->tempCacheAttributes() as $attr)
		    $data[$attr] = $this->$attr;

		$data['time'] = time();
		Yii::app()->cache->set(self::TEMPCACHE_KEY . Yii::app()->user->id, serialize($data));
		return $data['time'];
	}

	public function clearTempCache()
	{
		Yii::app()->cache->delete(self::TEMPCACHE_KEY . Yii::app()->user->id);
		return true;
	}

	public function loadTempCache()
	{
		$data = unserialize(Yii::app()->cache->get(self::TEMPCACHE_KEY . Yii::app()->user->id));
		$this->attributes = $data;
		$this->id = isset($data['id']) ? $data['id'] : null;
		return isset($data['time']) ? $data['time'] : false;
	}

	public function hasTempCache()
	{
	    return (Yii::app()->cache->get(self::TEMPCACHE_KEY . Yii::app()->user->id)) ? true : false;
	}

	/**
	 * 重建标签
	 */
	public function rebuildTagFrequency()
	{
	    $tag = Tag::model();
	    $tag->deleteAll();
	    $rs = $this->findAll();
	    foreach ($rs as $item)
	        Tag::model()->updateFrequency($item->tag, '');
	}

	public function publish($id, $option = false)
	{
	    $option = (boolean)$option;
        return $this->updateByPk($id, array('publish' => $option)) ? $option : null;
	}

    public function subPostContent($url = '#', $str = 'more', $mark = '&lt;!--more--&gt;')
    {
        if (false !== ($pos = strpos($this->content,$mark))){
            return substr($this->content, 0, $pos)
            . CHtml::tag('div', array('class' => 'more-link'), CHtml::link($str, $url));
        } else
            return $this->content;
    }

    public function getViewContent($tag = 'span', $mark = '&lt;!--more--&gt;')
    {
        return str_replace($mark, CHtml::tag($tag, array('id' => 'more' . $this->id), null) . '<br/>', $this->content);
    }

    /**
     * 增加点击量
     */
    public function autoClickNum()
    {
        return $this->updateCounters(array('click_num' => 1), 'id = :id', array(':id' => $this->id));
    }

    /**
     * add a comment
     * @param Comment $comment
     */
    public function addComment(Comment $comment)
    {
        $comment->post_id = $this->id;
        return $comment->save();
    }
}